<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import type { Ref } from 'vue';
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { accountPwdFormSchema } from './account.data';
  import {
    getDistrictList,
    editAccountPwd,
    addAccountList,
    isAccountExist,
  } from '/@/api/demo/system';

  import {
    AccountParams,
    DeptListItem,
    MenuParams,
    RoleParams,
    DistrictParams,
    RolePageParams,
    DistrictListItem,
    MenuListGetResultModel,
    DeptListGetResultModel,
    AccountListGetResultModel,
    RolePageListGetResultModel,
    RoleListGetResultModel,
    DistrictListGetResultModel,
  } from '/@/api/demo/model/systemModel';
  import debounce from 'lodash.debounce';
  import { encryptByMd5 } from '/@/utils/cipher';

  import { useUserStore } from '/@/store/modules/user';

  export default defineComponent({
    name: 'AccountPwdModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const rowId = ref('');
      const rowName = ref('');
      const refListDist = ref([]) as Ref<any[]>;
      const userStore = useUserStore();

      const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
        labelWidth: 100,
        size: 'small',
        schemas: accountPwdFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      function findAllNodes(val: any[], valOri: String[], jurisdictionCodes: String[]) {
        valOri.forEach((element) => {
          let fd = val.find((x) => x.id == element);
          if (fd) {
            if (jurisdictionCodes.indexOf(fd.regionCode) < 0) {
              jurisdictionCodes.push(fd.regionCode);
            }
            findAllNodes(val, [fd.parentId], jurisdictionCodes);
          }
        });
      }

      const AccValidator = function (_, value, _callback) {
        if (!value) {
          _callback();
          return;
        }

        isAccountExist(value)
          .then((d) => {
            if (d) {
              _callback('用户已存在');
            } else {
              _callback();
            }
          })
          .catch((err) => {
            _callback(err.message || '验证失败');
          });
      };

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        rowId.value = data.record.number;
      });

      const getTitle = computed(() => '修改密码2');

      async function handleSubmit() {
        try {
          const values = await validate();

          //const allCodes = [];

          //findAllNodes(refListDist.value, values.jurisdictionCodes, allCodes);
          //values.jurisdictionCodes = allCodes;
          setModalProps({ confirmLoading: true });
          // TODO custom api
          values.userNumber = rowId.value;
          values.pwd = encryptByMd5(values.pwd);
          await editAccountPwd(values);
          console.log(values);
          closeModal();
          emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
        } catch (ex) {
          console.log(ex);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
